import { serialize } from '@/util/util';
import { getStore } from '../util/store';
import NProgress from 'nprogress'; // progress bar
import errorCode from '@/const/error-code';
import router from '@/router/router';
import { Message, MessageBox } from 'element-ui';
import 'nprogress/nprogress.css';
import qs from 'qs';
import store from '@/store'; // progress bar style
// axios.defaults.timeout = 30000
// 返回其他状态吗
axios.defaults.validateStatus = function(status) {
    return status >= 200 && status <= 500; // 默认的
};
// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress Configuration
NProgress.configure({
    showSpinner: false
});

window.needLogin = false;
// 阻止重复请求
let requestList = [];
let CancelToken = axios.CancelToken;

// HTTPrequest拦截
axios.interceptors.request.use(
    (config) => {
        NProgress.start(); // start progress bar
        let access = !requestList.some((i) => {
            // url和传参都相同是 判断为相同请求
            return i.url == config.url && JSON.stringify(config.params) == JSON.stringify(i.params) && JSON.stringify(config.data) == JSON.stringify(i.data);
        });
        let cancel;
        let apiArr = [
            '/cp/statistics/tendency',
            '/cms/shard/upload',
            '/sockjs-node/info',
            '/cp/mediumgroup',
            '/admin/dict/type/job_execute_status',
            '/admin/dict/type/job_status',
            '/cp/common/upload',
            '/admin/sys-file/upload'
        ];
        if (access) {
            requestList.push({
                url: config.url,
                params: config.params,
                data: config.data
            });
        } else {
            config.cancelToken = new CancelToken(function executor(c) {
                //本次axios请求的配置添加cancelToken
                cancel = {
                    url: config.url,
                    f: c
                };
                if (!apiArr.includes(config.url)) {
                    cancel.f();
                }
            });
        }
        const TENANT_ID = getStore({ name: 'tenantId' });
        const corps = getStore({ name: 'corps' });
        const isToken = (config.headers || {}).isToken === false;
        const token = store.getters.access_token;
        if (token && !isToken) {
            config.headers['Authorization'] = 'Bearer ' + token; // token
        }
        if (TENANT_ID) {
            config.headers['Madp-Tenant-Id'] = TENANT_ID; // 租户ID
        }
        if (corps && corps.corpId) {
            config.headers['Madp-Corp-Id'] = corps.corpId;
        }

        // headers中配置serialize为true开启序列化
        if (config.method === 'post' && config.headers.serialize) {
            config.data = serialize(config.data);
            delete config.data.serialize;
        }

        if (config.method === 'get') {
            config.paramsSerializer = function(params) {
                return qs.stringify(params, { arrayFormat: 'repeat' });
            };
        }
        if (config.url.includes('/cp/corp')) {
            config.timeout = 60000;
        } else if (config.url.includes('/cp/common/upload')) {
            config.timeout = 120000;
        } else {
            config.timeout = 30000;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// HTTPresponse拦截
axios.interceptors.response.use(
    (res) => {
        requestList = requestList.filter((i) => i.url != res.config.url);
        NProgress.done();
        const status = Number(res.status) || 200;
        const message = res.data.msg || errorCode[status] || errorCode['default'];
        if (status === 200 && res.data.code === 0) {
            // 正常接口
            return Promise.resolve(res);
        } else if (status === 200 && res.config.url == '/auth/oauth/token') {
            // 处理登录接口
            return Promise.resolve(res);
        } else if (status === 401 && !window.needLogin) {
            window.needLogin = true;
            MessageBox.confirm('令牌状态已过期，请点击重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                type: 'warning',
                showClose: false,
                showCancelButton: false,
                closeOnClickModal: false,
                closeOnPressEscape: false,
                closeOnHashChange: false
            })
                .then(() => {
                    store.dispatch('FedLogOut').then(() => {
                        localStorage.setItem('needReload', 1);
                        router.push({
                            path: '/login'
                        });
                    });
                })
                .catch(() => {});
            return;
        } else if (status !== 200 || res.data.code === 1) {
            if (!window.needLogin) {
                Message({
                    message: message,
                    type: 'error'
                });
            }
            return Promise.reject(res);
        }
        return res;
    },
    (error) => {
        NProgress.done();
        return Promise.reject(new Error(error));
    }
);

export default axios;
